<template>
	<view class="main" style="background-color: #FAFAFA;">
		<view class="noSearch" v-if="inputList.length==0">
			<div style="height: 100px;"></div>
			<view class="a" v-show="!isOk">
				<div style="height: 100px;"></div>
				<u-loading-icon mode="circle" size="50px"></u-loading-icon>
			</view>
			<view class="b" v-show="isOk">
				<u-empty mode="search" text="暂无数据"></u-empty>
			</view>
		</view>
		<view v-if="inputList.length!=0">
			<!-- 选择器 -->
			<div style="padding-top: 2px;background-color: #FFF;"><u-line></u-line></div>
			<view class="chooses" style="padding: 10px 10px;background-color: #FFF;display: flex;margin-bottom: 10px;">
				<view class="temp" @click="inputStatus=true"
					style="display: flex;height: 40px;width: 100%;border:1px #FF5500 solid;border-radius: 5px;justify-content: space-between;align-items: center;">
					<view style="padding-left: 8px;color: #303133;">{{inputValue}}</view>
					<u-icon name="arrow-down" style="padding-right: 6px;"></u-icon>
				</view>
				<!-- <u-input  @focus="inputStatus=true" :value="inputValue"   :custom-style="{borderRadius:'5px'}"></u-input> -->
				<!-- <u-button @click="inputStatus=true" icon="list-dot" icon-color="#FFF" :custom-style="{backgroundColor:'#FF5500',borderRadius:'5px',width:'40px',marginLeft:'10px'}"></u-button> -->
			</view>
			<u-picker @confirm="handleConfirm" :defaultIndex="[getDefault()]" @close="inputStatus=false"
				@cancel="inputStatus=false" :show="inputStatus" :columns="inputList" keyName="siteName"
				closeOnClickOverlay></u-picker>

			<!-- 显示页 -->
			<view class="now" style="">
				<view class="title" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">实时监测数据</view>
				<view><u-line></u-line></view>
				<view class="content" style="padding: 15px 16px 0px 16px;background-color: #FFFFFF;">
					<u-row customStyle="padding-bottom:15px" v-for="(item, index) in currentDataList" :key="index">
						<u-col span="3" customStyle="color:#999999">
							<view>{{item.pointName}}</view>
						</u-col>
						<u-col span="3" customStyle="text-align:center">
							<view>{{item.value}}{{ getUnit(item) }}</view>
						</u-col>
						<u-col span="6" customStyle="text-align:right">
							<view>{{item.lastUpdated.slice(5)}} </view>
						</u-col>
					</u-row>
				</view>
			</view>
			<view class="old" style="margin-top: 10px;">
				<view class="title" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">历史监测数据</view>
				<view><u-line></u-line></view>
				<view class="content" style="background-color: #FFF;">
					<view class="intitle" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">数据时间范围
					</view>
					<view class="tags" style="display: flex;justify-content: center;">
						<view v-for="(item, index) in dateDruingList" :key="index" :style="getStyle(index)">
							<u-tag :text="item.text" :plain="!item.checked" shape="circle" type="warning" :name="index"
								@click="handDateClick">
							</u-tag>
						</view>
					</view>

					<view class="intitle" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">自定义时间
					</view>
					<view class="sj" style="display: flex;padding: 0px 16px;align-items: center;">
						<view @click="a()">
							<u--input placeholder="开始时间" border="surround" v-model="selfTimeDuring.start"
								suffixIcon="calendar-fill" readonly></u--input>
						</view>
						<view style="">{{'至'}}</view>
						<view @click="b()">
							<u--input placeholder="结束时间" border="surround" v-model="selfTimeDuring.end" readonly
								suffixIcon="calendar-fill"></u--input>
						</view>
					</view>

					<view class="intitle" style="padding: 10px 16px 5px 16px;height: 26px;background-color: #FFFFFF;">
						选择监测项目</view>
					<u-checkbox-group placement="row" v-model="indexList" @change="handChangePoint"
						style="padding: 0px 16px;display: flex;flex-wrap: wrap;">
						<u-checkbox :customStyle="{marginRight: '10px',marginTop:'5px'}"
							v-for="(item, index) in currentDataList" activeColor="#f9ae3d" :key="index"
							:label="item.pointName" :name="item.pointCode" :disabled="!ischange">
						</u-checkbox>
					</u-checkbox-group>

					<view class="chars"
						style="padding: 10px 16px 10px 0px;display: flex;flex-direction: column;justify-content:center;align-items: center;">
						<u--text :text="`${info.xmmc}-${info.facilities_type_name}`" :block="true"
							customStyle="width:70vw;textAlign:center;margin-left:16px" :lines="2" align="center"
							:bold="true"></u--text>
						<view class="char" style="height: 260px;width: 100%;">
							<qiun-data-charts type="area" :opts="opts" :chartData="chartData" />
						</view>
					</view>

				</view>
			</view>

			<!-- 日期弹出选择框 -->
			<u-datetime-picker ref="startPicker" :show="startTimeshow" v-model="queryParam.start" @cancel="startTimeshow=false"
				@confirm="timeconfirm('start',$event)" mode="datetime"></u-datetime-picker>
			<u-datetime-picker ref="endPicker" :show="endTimeShow" v-model="queryParam.end" @cancel="endTimeShow=false"
				@confirm="timeconfirm('end',$event)" mode="datetime"></u-datetime-picker>
		</view>
	</view>
</template>

<script>

import croods from '@/common/croods-1.3.3.js';     window.croods = croods;  window.hydra =  require('../../../../common/wst_hydra-1.0.0.js');


	import coordtransform from 'coordtransform';
	import {
		getHisAggData,
		getFactiesData
	} from '@/common/api.js';
	export default {
		props: ['info'],
		data() {
			return {
				/* 搜索 */
				isOk: false,
				ischange: true,
				inputValue: '',
				inputStatus: false,
				inputList: [],

				startTimeshow: false,
				endTimeShow: false,
				chartData: {},
				queryParam: {
					siteId: '',
					start: Number(new Date()) - 2 * 60 * 60 * 1000,
					end: Number(new Date()),
					aggregation: 'first',
					index: '',
					interval: 'm',
					value: '5',
				},
				selfTimeDuring: {
					start: '',
					end: '',
				},
				currentDataList: [],
				indexList: [],
				loadingType: '1',
				opts: {
					color: ["#00FCF0"],
					padding: [15, 50, 0, 15],
					enableScroll: false,
					legend: {},
					dataLabel: false,
					dataPointShape: false,
					xAxis: {
						disableGrid: true,
						labelCount: 3
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
						tofix: 2,
						splitNumber: 5
					},
					extra: {
						area: {
							type: "curve",
							opacity: 0.2,
							addLine: true,
							width: 2,
							gradient: true,
							activeType: "hollow"
						}
					}
				},
				dateDruingList: [{
						checked: true,
						text: '2小时',
						code: '2'
					},
					{
						checked: false,
						text: '6小时',
						code: '6'
					},
					{
						checked: false,
						text: '12小时',
						code: '12'
					},
					{
						checked: false,
						text: '24小时',
						code: '24'
					},
					{
						checked: false,
						text: '48小时',
						code: '48'
					}
				],
			}
		},
		methods: {
			a() {
				if (this.ischange) {
					this.startTimeshow = true;
				}
			},
			b() {
				if (this.ischange) {
					this.endTimeShow = true;
				}
			},
			timeconfirm(e, newValue) {
				const timeFormat = uni.$u.timeFormat;
				if (e == 'start') {
					this.queryParam.start = newValue.value;
					this.selfTimeDuring.start = timeFormat(this.queryParam.start, 'yyyy-mm-dd hh:MM');
					this.startTimeshow = false;
				}
				if (e == 'end') {
					this.queryParam.end = newValue.value
					this.selfTimeDuring.end = timeFormat(this.queryParam.end, 'yyyy-mm-dd hh:MM');
					this.endTimeShow = false;
				}
				if (this.selfTimeDuring.start && this.selfTimeDuring.end) {
					const start = new Date(this.selfTimeDuring.start)
					const end = new Date(this.selfTimeDuring.end)
					let time = Math.abs(end-start)
					const bi = 1000 * 60 * 60 * 24 * 31
					if(time>bi){
						uni.$u.toast('最大自定义时间范围为31天，请重新选择')
						this.selfTimeDuring.start = ''
						this.selfTimeDuring.end = ''
						this.queryParam.start = Number(new Date())- 2*60*60*1000
						this.$refs.startPicker.innerValue = this.queryParam.start
						this.queryParam.end = Number(new Date())
						this.$refs.endPicker.innerValue = this.queryParam.end
						return
					}else{
						this.getHistoryData();
					}
				}
			},
			async getHistoryData() {
				try {
					this.chartData = {}
					this.ischange = false
					const param = this.queryParam;
					if (!param.start || !param.end) {
						return;
					};
					/* const timeFormat = uni.$u.timeFormat;
					param.start = timeFormat(this.queryParam.start, 'yyyy-mm-dd hh:MM:ss');
					param.end = timeFormat(this.queryParam.end, 'yyyy-mm-dd hh:MM:ss'); */
					
					if (typeof this.queryParam.start === 'number') {
						const datax = new Date(this.queryParam.start)
						param.start = datax.toLocaleString('sv-SE').replace('T', ' ')
					}else{
						param.start = this.queryParam.start
					}
					if (typeof this.queryParam.end === 'number') {
						const datax = new Date(this.queryParam.end)
						param.end = datax.toLocaleString('sv-SE').replace('T', ' ')
					}else{
						param.end = this.queryParam.end
					}
					
					const indexs = this.indexList;
					const data = {
						categories: [],
						series: []
					};
					let zeroSet = new Set()
					for (let index of indexs) {
						param.index = index;
						const site = this.currentDataList.find(item => item.pointCode == index);
						let name = ''
						if (site) {
							name = site.pointName + '(' + site.unit + ')'
						}
						param.siteId = site?.siteId;
						if (typeof this.queryParam.start === 'number') {
							const datax = new Date(this.queryParam.start)
							param.start = datax.toLocaleString('sv-SE').replace('T', ' ')
						}else{
							param.start = this.queryParam.start
						}
						if (typeof this.queryParam.end === 'number') {
							const datax = new Date(this.queryParam.end)
							param.end = datax.toLocaleString('sv-SE').replace('T', ' ')
						}else{
							param.end = this.queryParam.end
						}
						const result = await getHisAggData(param);
						if (result) {

							const list = result
							for (let i = 0; i < list.length; i++) {
								let value = Math.floor(list[i].value * 100) / 100
								zeroSet.add(value);
								if (zeroSet.size == 5) {
									break
								}
							}
							const serie = {
								name: name,
								data: []
							}
							const categories = [];
							result.forEach(item => {
								categories.push(item.time.substr(5));
								serie.data.push(item.value);
							});
							data.series.push(serie);
							data.categories = categories;
						}
					}
					this.chartData = data;
					if (zeroSet.size < 5) {
						if (zeroSet.size > 1) {
							let values = Array.from(zeroSet)
							a: for (let i = 0; i < values.length - 1; i++) {
								for (let j = i + 1; j < values.length; j++) {
									if ((Math.abs(values[i] - values[j]) > 0.05) || (Math.abs(values[i] - values[
											j]) < -0.05)) {
										this.opts.yAxis.splitNumber = 5
										break a;
									}
								}
							}
						} else {
							this.opts.yAxis.splitNumber = zeroSet.size
						}
					} else {
						this.opts.yAxis.splitNumber = 5
					}
					this.ischange = true
					this.isOk = true
				} catch (error) {
					// 处理请求失败的逻辑
					console.error(error);
				}

			},
			handChangePoint(n) {
				this.indexList = n;
				this.getHistoryData();
			},
			async getMonitordata(data) {
				try {
					this.loadingType = 1;
					/* const result = await getFactiesData({id:this.info.id}); */
					const result = data
					if (Object.keys(result).length !== 0) {
						let currentDatas = [];
						let indexList = [];
						for (let item in result) {
							for (let datas of result[item]) {
								currentDatas = currentDatas.concat(datas.appMonitorPointDataDtoList);
							}
						}
						this.currentDataList = currentDatas;
						this.indexList.push(this.currentDataList[0].pointCode);
						this.getHistoryData();
						this.isOk = true
					} else {
						uni.$u.toast('设施下暂无数据');
						this.isOk = true
						this.loadingType = 0;
					}
				} catch (error) {
					// 处理请求失败的逻辑
					console.error(error);
				}
			},
			handDateClick(name) {
				if (this.ischange) {
					this.dateDruingList.map((item, index) => {
						item.checked = index === name ? true : false
					})
					this.queryParam.start = Number(new Date()) - this.dateDruingList[name].code * 60 * 60 * 1000;
					this.queryParam.end = Number(new Date());
					this.getHistoryData();
				}
			},
			getUnit(item) {
				if (item.value || item.value == 0 || item.value === 0.0) {
					return item.unit
				} else {
					return
				}
			},
			getStyle(index) {
				if (index == 0) {
					return
				} else {
					return {
						'margin-left': '10px'
					}
				}
			},

			/* 获取搜索框数据 */
			async getInputList() {
				let that = this
				const result = await getFactiesData({
					id: this.info.id
				});
				let temp = []
				for (let key in result) {
					let arr = result[key];
					arr.forEach(item => {
						temp.push(item)
					})
				}
				if (temp.length > 0) {
					that.inputValue = temp[0].siteName
					that.inputList.push(temp)

					let zoo = temp[0].siteSubType
					let data = {}
					let test = [temp[0]]
					data[zoo] = test
					that.getMonitordata(data)
				}else{
					this.isOk = true
				}

			},
			getDefault() {
				if (this.inputList[0]) {
					let index = this.inputList[0].findIndex(obj => obj.siteName === this.inputValue);
					return index
				} else {
					return
				}
			},
			handleConfirm(value) {

				this.startTimeshow = false;
				this.endTimeShow = false;
				this.chartData = {};
				this.queryParam = {
					siteId: '',
					start: Number(new Date()) - 2 * 60 * 60 * 1000,
					end: Number(new Date()),
					aggregation: 'first',
					index: '',
					interval: 'm',
					value: '5',
				};
				this.selfTimeDuring = {
					start: '',
					end: '',
				};
				this.currentDataList = [];
				this.indexList = [];
				this.dateDruingList.forEach(item => {
					if (item.code == 2) {
						item.checked = true
					} else {
						item.checked = false
					}
				})

				let temp = value.value[0]
				this.inputValue = temp.siteName
				let zoo = temp.siteSubType
				let data = {}
				let test = [temp]
				data[zoo] = test
				this.getMonitordata(data)
				this.inputStatus = false
			}
		},
		mounted() {

			this.$nextTick(() => {
				this.isOk = false
				this.getInputList();
				/* this.getMonitordata(); */
			});
		},
		onShow() {
			document.body.style.overflow = 'auto';
		}

	};
</script>

<style lang="scss" scoped>
	.title {
		font-family: 'PingFangSC-Medium';
		font-size: 16px;
		color: #212121;
		font-weight: 550;
	}

	.intitle {
		font-family: 'PingFangSC-Regular';
		font-size: 15px;
		color: #212121;
		font-weight: 400;
	}
</style>